// $_FILEHEADER_BEGIN ***************************
// 版权声明:Timer
// Copyright © 2015 - Timer All Rights Reserved
// 文件名称: BrushFaceVC.m
// 创建日期: 15/12/6
// 创 建 人: 甄鑫
// 文件说明: <#content#>
// $_FILEHEADER_END ******************************


#import "BrushFaceVC.h"
#import "NavHelper.h"
#import "BrushFaceHomeHeaderView.h"
#import "BrushStaticClass.h"
#import "HomeFinanceBetweenView.h"
#import "HomeFinanceCell.h"
#import "View+MASAdditions.h"
#import "FinanceReqModel.h"
#import "CanBeBrrowedVC.h"
#import <UIButton+WebCache.h>
#import "DeviceInfo.h"
#import "BorrowHomeCenterNumV.h"
#import "JieRuCell.h"
#import "MeStatus.h"
#import "JieRuJieChuVC.h"

@interface BrushFaceVC ()<UITableViewDelegate,UITableViewDataSource>
{
    UITableView *_tableView;
    UIScrollView *_scrollView;
    UIScrollView *_buttonScrollView;
    BrushFaceHomeHeaderView *_tableViewHeaderView;
    BrushFaceHomeHeaderView *_jieKuanHeaderView;
    HomeFinanceBetweenView *_homeBetweenView;
    FinanceReqModel *_reqmodel;
    NSMutableArray *_dataArray;
    BOOL _requestSuccess;
    int _currentPage;
}
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *switchButtonX;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *jiekuanLabelX;
@property (weak, nonatomic) IBOutlet UILabel *jiekuanLabel;
@property (weak, nonatomic) IBOutlet UIView *backGroundView;


@end

@implementation BrushFaceVC

#pragma mark - life cercle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    // Do any additional setup after loading the view from its nib.
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginOut) name:@"LOGINOUT" object:nil];
    
    [self UIConfig];
    _dataArray = [[NSMutableArray alloc] init];
    _requestSuccess = NO;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    
    NSString *newrequestStr = [NSString stringWithFormat:@"%@/hope/getinvestforapp.json",SERVICE_ADRESS];
    AFHTTPRequestOperationManager *borromanager = [AFHTTPRequestOperationManager manager];
    [borromanager GET:newrequestStr parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:operation.responseData options:0 error:nil];
        
        [self addHeaderViewDataWithJson:json];
        
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        
    }];
    
    
    if ([MeStatus sharedInstance].userAccountStatus == USER_ACCOUNT_STATUS_VERIFY) {
        [self loginSuccessLoadDataStart];
    }
    
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - custonMethods

- (void)loginSuccessLoadDataStart{
    _reqmodel = [FinanceReqModel SceneModel];
    [_reqmodel hope_listFriendHopeWithCurPage:0 andRPP:10 andCB:^(NSMutableArray *resultArray) {
        [_dataArray removeAllObjects];
        [_dataArray addObjectsFromArray:resultArray];
        [_tableView reloadData];
    }];
    _requestSuccess = YES;
    _currentPage = 0;
    

    NSString *requestStr = [NSString stringWithFormat:@"%@/hope/getinterestindexinfo.json",SERVICE_ADRESS];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [[AFHTTPResponseSerializer alloc] init];
    [manager GET:requestStr parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:operation.responseData options:0 error:nil];
        _homeBetweenView.numLabel.text = [NSString stringWithFormat:@"%@%%",json[@"hoperate"]];
        _homeBetweenView.moneyLabel.text = [NSString stringWithFormat:@"%@",json[@"income"]];
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        
    }];
    
    
}
- (void)UIConfig{
    [self hideNav];
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64)];

    _scrollView.contentSize = CGSizeMake(SCREEN_WIDTH*2, 0);
    _scrollView.contentOffset = CGPointMake(SCREEN_WIDTH, 0);
    _scrollView.backgroundColor = UIColorFromRGB(ColorValueForBackView_Gray);
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.pagingEnabled = YES;
    _scrollView.bounces = NO;
    _scrollView.delegate = self;
    [_backGroundView addSubview:_scrollView];
    _homeBetweenView = [HomeFinanceBetweenView loadBundleNib];
    [self configLiCaiDuanView];
    [self configJieKuanDuanView];
}
//借款端页面
- (void)configJieKuanDuanView{
    _jieKuanHeaderView = [BrushFaceHomeHeaderView loadBundleNib];
    _jieKuanHeaderView.frame = CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_WIDTH/16.0*11);
    
    [_scrollView addSubview:_jieKuanHeaderView];
    
    _buttonScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH, _jieKuanHeaderView.frame.size.height+_jieKuanHeaderView.frame.origin.y, SCREEN_WIDTH, _scrollView.frame.size.height-_jieKuanHeaderView.frame.size.height-49)];
    _buttonScrollView.pagingEnabled = YES;
    _buttonScrollView.bounces = NO;
    [_scrollView addSubview:_buttonScrollView];
    
    NSMutableArray *buttonArray = [NSMutableArray arrayWithObjects:@"brushFace_ReasonItem0@2x",@"brushFace_ReasonItem1@2x",@"brushFace_ReasonItem2@2x",@"brushFace_ReasonItem3@2x",@"brushFace_ReasonItem4@2x",@"brushFace_ReasonItem5@2x", nil];
    [BrushStaticClass addJieKuanReasonButtonWith:_buttonScrollView fromMutableArray:buttonArray];
}
//理财端页面
- (void)configLiCaiDuanView{
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64-49) style:UITableViewStylePlain];
    _tableViewHeaderView = [BrushFaceHomeHeaderView loadBundleNib];
    _tableViewHeaderView.frame = CGRectMake(0, 0, _tableView.frame.size.width, SCREEN_WIDTH/16.0*11);
    
    _tableView.backgroundColor = UIColorFromRGB(ColorValueForBackView_Gray);
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableHeaderView = _tableViewHeaderView;
    [_scrollView addSubview:_tableView];
    [self setRefresh];
}

#pragma mark - action
- (IBAction)addButtonClick:(id)sender {
    if ([BrushStaticClass isNeedLogin:YES]) {
        return;
    }else{
        [NavHelper gotoAddFriendVC];
    }
}
- (IBAction)switchButtonClick:(id)sender {
    if ([BrushStaticClass isNeedLogin:YES]) {
        return;
    }
        if (_switchButtonX.constant == 0) {
            [_switchButtonX setConstant:63];
            [_jiekuanLabelX setConstant:63];
            _jiekuanLabel.text = @"理财";
            _scrollView.contentOffset = CGPointMake(0, 0);
        }else{
            [_switchButtonX setConstant:0];
            [_jiekuanLabelX setConstant:0];
            _jiekuanLabel.text = @"借款";
            _scrollView.contentOffset = CGPointMake(SCREEN_WIDTH, 0);
        }
}


#pragma mark - scrollView delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if ([BrushStaticClass isNeedLogin:NO]) {
        _scrollView.contentOffset = CGPointMake(SCREEN_WIDTH, 0);
    }
    if ([scrollView isEqual:_scrollView]) {
        if (_scrollView.contentOffset.x/SCREEN_WIDTH==0) {
            [_switchButtonX setConstant:63];
            [_jiekuanLabelX setConstant:63];
            _jiekuanLabel.text = @"理财";
            [self loginSuccessLoadDataStart];
        }else{
            [_switchButtonX setConstant:0];
            [_jiekuanLabelX setConstant:0];
            _jiekuanLabel.text = @"借款";
        }
    }
}
#pragma mark - 上拉下拉
- (void)setRefresh{
    @weakify (self);
    [_tableView addPullToRefreshWithActionHandler:^{
        @strongify (self);
        self->_currentPage = 0;
        [self->_reqmodel hope_listFriendHopeWithCurPage:0 andRPP:10 andCB:^(NSMutableArray *resultArray) {
            [self->_dataArray removeAllObjects];
            [self->_dataArray addObjectsFromArray:resultArray];
            [self->_tableView reloadData];
            [self->_tableView endAllRefreshingWithEnd:NO];
            NSLog(@"%d",self->_currentPage);
        }];
    }];
    [_tableView addInfiniteScrollingWithActionHandler:^{
        @strongify (self);
        [self->_reqmodel hope_listFriendHopeWithCurPage:++self->_currentPage  andRPP:10 andCB:^(NSMutableArray *resultArray) {
            [self->_dataArray addObjectsFromArray:resultArray];
            [self->_tableView reloadData];
            if (resultArray.count<10) {
               [self->_tableView endAllRefreshingWithEnd:YES];
            }else{
               [self->_tableView endAllRefreshingWithEnd:NO];
            }
            NSLog(@"%d",self->_currentPage);
        }];
    }];
    
}

#pragma mark - tableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"HomeFinanceCell";
    HomeFinanceCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [HomeFinanceCell loadBundleNib];
    }
    NSDictionary *detailDict = [_dataArray objectAtIndex:indexPath.row];
    cell.nickNameLabel.text = [NSString stringWithFormat:@"%@",[detailDict objectForKey:@"fullname"]];
    [cell.iconButton sd_setBackgroundImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HEADERIMAGE_FETCH,[detailDict objectForKey:@"localid"]]] forState:UIControlStateNormal];
    cell.reasonLabel.text = [NSString stringWithFormat:@"%@",[detailDict objectForKey:@"summary"]];
    if ([detailDict[@"rlevel"] isEqual:[NSNull null]]||[detailDict[@"rlevel"] integerValue]==1) {
        cell.friendImageView.text = @" 朋友 ";
    }else {
        cell.friendImageView.text = @" 朋友的朋友 ";
    }
    if ([[detailDict objectForKey:@"isborrow"] boolValue]) {
        cell.borrowMeImageView.hidden = NO;
    }else{
        cell.borrowMeImageView.hidden = YES;
    }
    cell.userid = [detailDict objectForKey:@"localid"];
    cell.moneyLabel.text = [NSString stringWithFormat:@"%@",detailDict[@"hopeamount"]];
    cell.lixiLabel.text = [NSString stringWithFormat:@"%@",detailDict[@"hoperate"]];
    if ([[NSString stringWithFormat:@"%@",detailDict[@"priod"]] integerValue]==0) {
        cell.dateLabel.text = [NSString stringWithFormat:@"%@天",detailDict[@"days"]];
    }else{
        cell.dateLabel.text = [NSString stringWithFormat:@"%@个月",detailDict[@"priod"]];
    }
    cell.borrowNumberLabel.text = [NSString stringWithFormat:@" %@人已借",detailDict[@"investcount"]];
    cell.currentType = [[NSString stringWithFormat:@"%@",detailDict[@"status"]] integerValue];
    cell.hopeId = [NSString stringWithFormat:@"%@",detailDict[@"id"]];
    NSInteger currentTime = [[DeviceInfo getCurDeviceTimeStr] integerValue];
    NSInteger endTime = [[NSString stringWithFormat:@"%@",detailDict[@"expiredate"]] integerValue];
    NSInteger temp = (endTime - currentTime)/1000/60;
    NSInteger hour = temp/60;
    NSInteger minute = temp%60;
    NSString *time;
    if(hour<=0){
        if (minute <= 0) {
            time = @"剩余0分钟";
        }else{
            time = [NSString stringWithFormat:@"剩余%ld分钟",minute];
        }
    }else{
        if (minute <= 0) {
            time = [NSString stringWithFormat:@"剩余%ld小时",hour];
        }else{
            time = [NSString stringWithFormat:@"剩余%ld小时%ld分钟",hour,minute];
        }
    }
    cell.timeLabel.text = time;
    if ([[NSString stringWithFormat:@"%@",detailDict[@"status"]] integerValue]==1||[[NSString stringWithFormat:@"%@",detailDict[@"status"]] integerValue]==0||[[NSString stringWithFormat:@"%@",detailDict[@"status"]] integerValue]==11||[[NSString stringWithFormat:@"%@",detailDict[@"status"]] integerValue]==12) {
        [cell cellSetPrecent:[[NSString stringWithFormat:@"%@",detailDict[@"investrate"]] floatValue]];
    }
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 172;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSInteger status = [[NSString stringWithFormat:@"%@",[[_dataArray objectAtIndex:indexPath.row] objectForKey:@"status"]] integerValue];
    NSString *hopeid = [NSString stringWithFormat:@"%@",[[_dataArray objectAtIndex:indexPath.row] objectForKey:@"id"]];
    [NavHelper gotoAssetsRecordVC:status andBaseType:TYPE_FINANCE andHopeId:hopeid];
}

#pragma mark - 数据处理
- (void)addHeaderViewDataWithJson:(NSDictionary *)json{
    NSMutableArray *array = [NSMutableArray array];
    NSMutableArray *array1 = [NSMutableArray array];
    NSArray *imarray = @[@"shuliandu@2x.PNG",@"xinshuouyindao@2x.PNG"];
    for (int i=0; i<2; i++) {
        UIImageView *imageView  = [[UIImageView alloc]init];
        imageView.image = [UIImage imageNamed:imarray[i]];
        [array addObject:imageView];
        UIImageView *imageView1  = [[UIImageView alloc]init];
        imageView1.image = [UIImage imageNamed:imarray[i]];
        [array1 addObject:imageView1];
    }
    
    [_tableViewHeaderView addSubviewToVScrollViewWithViewArray:array];
    [_jieKuanHeaderView addSubviewToVScrollViewWithViewArray:array1];
    
    
    [array removeAllObjects];
    if ([[NSString stringWithFormat:@"%@",json[@"investCount"]] integerValue]>1) {
        BorrowHomeCenterNumV *centerv = [BorrowHomeCenterNumV loadBundleNib];
        centerv.numLabel.text = [NSString stringWithFormat:@"%@",[json[@"investAmountView"] moneySegmentation]];
        [array addObject:centerv];
        UILabel *label = [[UILabel alloc] init];
        label.text = [NSString stringWithFormat:@"借款中%@笔",json[@"investCount"]];
        label.font = [UIFont systemFontOfSize:20];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = ColorDefaultOrange;
        [array addObject:label];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapToJieRu)];
        label.userInteractionEnabled = YES;
        [label addGestureRecognizer:tap];
    }else if([[NSString stringWithFormat:@"%@",json[@"investCount"]] integerValue]==1){
        BorrowHomeCenterNumV *centerv = [BorrowHomeCenterNumV loadBundleNib];
        centerv.numLabel.text = [NSString stringWithFormat:@"%@",[json[@"investAmountView"] moneySegmentation]];
        [array addObject:centerv];
        NSLog(@"harry---%@",json);
        JieRuCell *view = [JieRuCell loadBundleNib];
        [array addObject:view];
    }else if([[NSString stringWithFormat:@"%@",json[@"investCount"]] integerValue]<1){
        BorrowHomeCenterNumV *centerv = [BorrowHomeCenterNumV loadBundleNib];
        centerv.numLabel.text = [NSString stringWithFormat:@"%@",[json[@"investAmountView"] moneySegmentation]];
        [array addObject:centerv];
    }
    
    [_jieKuanHeaderView addSubViewToHScrollViewWithViewArray:array];
    [_tableViewHeaderView addSubViewToHScrollViewWithViewArray:[NSMutableArray arrayWithObject:_homeBetweenView]];
    
}


- (void)tapToJieRu{
    JieRuJieChuVC * _vc = [[JieRuJieChuVC alloc]initWithType:JIERU_TYPE];
    [_vc setHidesBottomBarWhenPushed:YES];
    _vc.isBorrowing = YES;
    [self.navigationController pushViewController:_vc animated:YES];
}
- (void)loginOut{
    _scrollView.contentOffset = CGPointMake(SCREEN_WIDTH, 0);
    
}
@end
